﻿<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="Microsoft.Web.Mvc" %>
<%@ Import Namespace="Br.Com.Quavio.Tools.Web.MVC" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Galeazi - Metais não ferrosos e aços inoxidáveis - Atendimento Online</title>
    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="Content-Language" content="pt-br" />
    <meta name="robots" content="all" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    
    <%= Html.FavIcon("~/Content/Images/Global/favicon.ico") %>
    
    <%= Html.Css("~/Content/Reset.css") %>
    <%= Html.Css("~/Content/Common.css")%>
    <%= Html.Css("~/Content/textformat.css")%>
    <%= Html.Css("~/Content/Atendimento.css")%>
    <%= Html.Css("~/Content/stickyfooter.css")%>

    <%= Html.Script("~/Scripts/util.js") %>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
    <%--<script src="http://static.quavio.com.br/files/cloudtalk/1.0.0/cloudtalk.min.js" type="text/javascript"></script>--%>
    <%= Html.Script("~/Scripts/1.0.0/cloudtalk.js") %>
    <%= Html.Script("~/Scripts/json2.js") %>
    <%= Html.Script("~/Scripts/jquery.sound.js")%>
    
    <script type="text/javascript">
        var sClientName;
        var sClientEmail;
        var bIsOnline = '<%= ViewData["Online"] %>';
        var sRoomName = '<%= ViewData["RoomName"] %>';
        var sBaseURL = '<%= Url.Content("~/Home.aspx/") %>';
        var sTunePath = '<%= Url.Content("~/Content/newmsg.wma") %>';

        // variable declarations
        var ePanelLogin,        // input panel with name and email prompt
            ePanelMessages,     // the whole message exchange panel
            eDivMessages,       // sent and received messages div
            eTxtMessage,        // input area for the message to be sent
            eTxtName,           // input field for client name
            eTxtEmail,          // input field for client email
            eBtnSubmit,         // submit message button
            eBtnJoin,           // join room button
            eLoadingImage,      // 'loading' image
            eLabelQueue,        // Label indicating the client position on the queue
            eLabelQueueSize,    // Label with the client position number
            bWaitingToJoin;     // Are we currently in the queue, waiting to join the room?

        var cloudTalk = new CloudTalk(sBaseURL);

        $(document).ready(function() {

            // assign elements
            ePanelLogin = $('#login-panel');
            ePanelMessages = $('#messages-panel');
            eDivMessages = $('#msgs-panel');
            eTxtMessage = $('textarea#input-area');
            eTxtName = $('input#txt-name');
            eTxtEmail = $('input#txt-email');
            eLoadingImage = $('.loading-image');
            eBtnSubmit = $('input#submit-button');
            eBtnJoin = $('input#enter-button');
            eLabelQueue = $('span#queue-indicator');
            eLabelQueueSize = $('span#queue-size');
            bWaitingToJoin = false;

            // hide panels
            eLoadingImage.hide();
            ePanelMessages.hide();
            eLabelQueue.hide();

            if (bIsOnline == "False") {
                $('div.not-available').show();
                ePanelLogin.hide();
            }

            eTxtMessage.keypress(onKeyPress);
            eBtnJoin.click(onJoinRoom);
            eBtnSubmit.click(onClickSubmit);
        });

        // text message key press event handler
        function onKeyPress(evt) {
            var keyPressEvent = (evt) ? evt : event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;

            // enter key press submits the message (if shift is not pressed)
            if (charCode == 13 && !keyPressEvent.shiftKey) {
                keyPressEvent.preventDefault(); // suppress the line break the line in the input field
                eBtnSubmit.click(); // programatically submit the form on ENTER key press
            }
        }

        // send message event handler
        function onClickSubmit() {
            cloudTalk.sendMessage(
                sRoomName,
                sClientEmail,
                eTxtMessage.val());

            appendOwnMessage(
                sClientName,
                Utils.getTime(),
                eTxtMessage.val());

            eTxtMessage.val('');   // clear the input field
        }

        // join room event handler
        function onJoinRoom(evt) {
            evt.preventDefault();

            if (eTxtName.val() == '' ||
                eTxtEmail.val() == '') {
                alert('Favor preencher todos os campos');
                return;
            }

            if (!Utils.isValidEmail(eTxtEmail.val())) {
                alert("Favor preencher um endereço de email válido");
                return;
            }

            eLoadingImage.show();

            sClientName = eTxtName.val();
            sClientEmail = eTxtEmail.val();

            cloudTalk.joinRoom(
                sRoomName,
                sClientName,
                sClientEmail,
                onRoomJoined,
                onRoomJoinFailed);
        }

        function onRoomJoined(data, textStatus) {
            eLoadingImage.hide();

            var retCode = data.Code;
            var retMsg = data.Message;

            if (retCode == 3) {
                // the room is currently full :( Wait in the line.
                eLabelQueue.show();
                eLabelQueueSize.text(data.Position);
                eBtnJoin.hide();
                bWaitingToJoin = true;
                getEvents();
                setUpQuitConfirmation();
                return;
            }
            else if (retCode != 1) {
                // error occurred.
                alert(retMsg);
            }
            else {
                setUpChat();
                getEvents();    // start comet streaming
            }
        }

        function setUpChat() {
            ePanelLogin.hide("normal");
            ePanelMessages.show('normal');
            setUpQuitConfirmation();
        }

        function setUpQuitConfirmation() {
            // bind window unload events
            window.onbeforeunload = function() { return "Se você sair, suas mensagens não serão mantidas!" };
            $(window).bind('unload', function() { cloudTalk.leaveRoom(sRoomName, sClientEmail); });
        }

        function onRoomJoinFailed(xhr, textStatus, errorThrown) {
            eLoadingImage.hide();

            alert(xhr.responseText);    // alert the failure
        }

        // makes an ajax request for new events for this client
        function getEvents() {
            cloudTalk.getEvents(
                sClientEmail,
                onEventsComplete,
                getEvents);
        }

        function appendOwnMessage(_sSender,
                               _sTimestamp,
                               _sMsg) {

            appendText("<div class=\"message\"><span class=\"client\">" + _sSender + " (" + _sTimestamp + "): </span>" + Utils.formatMessage(_sMsg) + "</div>");
        }

        // Appends text to the messages panel and scrolls it to the bottom
        function appendMessage(_sSender,
                               _sTimestamp,
                               _sMsg) {

            appendText("<div class=\"message\"><span>" + _sSender + " (" + _sTimestamp + "): </span>" + Utils.formatMessage(_sMsg) + "</div>");
        }

        function appendText(_sMessage) {
            eDivMessages.append(_sMessage);
            eDivMessages[0].scrollTop = eDivMessages[0].scrollHeight;
        }

        // Called when new message(s) have been received
        function onEventsComplete(data) {
            // update messages list
            var arrMessages = data;

            for (var i = 0; i < arrMessages.length; i++) {

                var theMessage = arrMessages[i];
                var sEventType = theMessage.EventType;

                if (bWaitingToJoin && sEventType == "RoomSpaceAvailable") {
                    // we've just received a message telling us that there is free space
                    // for us to join the room! cool :)
                    setUpChat();
                }
                else if (sEventType == "QueueSizeChanged") {
                    var msgObject = JSON.parse(theMessage.EventObject);

                    eLabelQueueSize.text(msgObject.QueueSize);
                }
                else if (sEventType == "Message" ||
                    sEventType == "EnterRoom" ||
                    sEventType == "LeaveRoom") {
                    
                    var msgObject = JSON.parse(theMessage.EventObject);

                    appendMessage(
                        theMessage.Sender,
                        theMessage.Timestamp,
                        msgObject.Message);

                    $.sound.play(sTunePath);
                }
            }

            getEvents();    // restart the events request
        }
    </script>
</head>
<body>
    <div id="wrap">
	    <div id="main" class="clearfix">
            <div class="chat-body">
                <div class="title">Atendimento Online <%--<span class="float-right"><a href="#">sair</a></span>--%></div>
                <%= Html.VirtualImage("~/Content/Images/Atendimento/logo.png") %>
                <div class="not-available">No momento, não existem posições disponíveis para seu atendimento. Por favor, tente novamente mais tarde.</div>
                <div id="login-panel">
                    Bem vindo ao nosso atendimento via chat!<br /><br />
                    <%= Html.Label("Nome:") %><%= Html.TextBox("Name", null, new { Class = "login-input", Id = "txt-name" })%><br />
                    <%= Html.Label("Email:") %><%= Html.TextBox("Email", null, new { Class = "login-input", Id = "txt-email" }) %><br />
                    <%= Html.SubmitButton("Entrar", "Entrar", new { Class = "enter-button", Id = "enter-button" })%>
                    <%= Html.Image(Url.Content("~/Content/Images/Atendimento/loading.gif"), new { Class = "loading-image" })%>
                    <span id="queue-indicator">Você está na posição <span id="queue-size">?</span> da fila. Por favor, aguarde.</span>
                </div>
                <div id="messages-panel">
                    <div class="messages-area" id="msgs-panel">
                    </div>
                    <%= Html.TextArea("Message", new { Class="input-area", Id="input-area" }) %>
                    <%= Html.SubmitImage("Enviar", "~/Content/Images/Atendimento/enviar.png", new { Class = "submit-button", Id = "submit-button" })%>
                </div>
            </div>
        </div>
    </div>
    <div class="chat-footer" id="footer">
        <a href="http://www.quavio.com.br/" target="_blank"><%= Html.VirtualImage("~/Content/Images/quavio.png", new { Class = "float-right" })%></a>            
    </div>
</body>
</html>
